package thread.wait;

/**
 * wait()/wait(int timeout):   让出当前CPU资源
 * notify()/notifyAll():    通知持有锁的其他线程可以不用继续等待，其他线程将在本线程运行结束后获取到CPU资源，进而继续执行
 *
 * @author wei.yang on 2018/8/7
 */
public class WaitThread {

    /**
     * 不可变对象
     */
    private static final Object FLAG = new Object();

    public static void main(String[] args) {
        new Thread(new Worker()).start();
        new Thread(new Worker1()).start();
    }

    static class Worker implements Runnable {

        @Override
        public void run() {
            synchronized (FLAG) {
                while (true) {
                    try {
                        System.out.println("work start");
                        FLAG.wait(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("work end");
                }
            }
        }
    }

    static class Worker1 implements Runnable {

        @Override
        public void run() {
            synchronized (FLAG) {
                while (true) {
                    System.out.println("work1 start");
                    try {
                        Thread.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("work1 end");
                }
            }
        }
    }
}
